package com.example.mydy;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.mydy.api.UserApi;
import com.example.mydy.model.CommonResponse;
import com.example.mydy.utils.NetworkUtils;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterActivity extends AppCompatActivity {
    private static final String TAG = "RegisterActivity";

    private EditText etUsername;
    private EditText etPassword;
    private EditText etConfirmPassword;
    private EditText etNickname;
    private EditText etInviteCode;
    private Button btnRegister;
    private Button btnBackToLogin;
    private ProgressBar progressBar;

    private UserApi userApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // 初始化API
        userApi = NetworkUtils.getUserApi();

        // 初始化视图
        initViews();
        
        // 检查服务器连接
        checkServerConnection();

        // 设置点击监听器
        btnRegister.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
            }
        });

        btnBackToLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish(); // 返回登录页面
            }
        });
    }

    private void checkServerConnection() {
        progressBar.setVisibility(View.VISIBLE);
        
        userApi.checkServerStatus().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                progressBar.setVisibility(View.GONE);
                
                if (!response.isSuccessful()) {
                    Log.e(TAG, "服务器状态检查失败: " + response.code());
                    Toast.makeText(RegisterActivity.this, "服务器连接异常，注册功能可能受限", Toast.LENGTH_SHORT).show();
                } else {
                    Log.d(TAG, "服务器连接正常");
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                Log.e(TAG, "服务器连接检查失败", t);
                Toast.makeText(RegisterActivity.this, "无法连接到服务器，请检查网络设置", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        etConfirmPassword = findViewById(R.id.et_confirm_password);
        etNickname = findViewById(R.id.et_nickname);
        etInviteCode = findViewById(R.id.et_invite_code);
        btnRegister = findViewById(R.id.btn_register);
        btnBackToLogin = findViewById(R.id.btn_back_to_login);
        progressBar = findViewById(R.id.progressBar);
    }

    private void register() {
        // 获取输入
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();
        String userNickname = etNickname.getText().toString().trim();
        String inviteCode = etInviteCode.getText().toString().trim();

        // 验证输入
        if (TextUtils.isEmpty(username)) {
            etUsername.setError("请输入用户名");
            etUsername.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            etPassword.setError("请输入密码");
            etPassword.requestFocus();
            return;
        }

        if (password.length() < 6) {
            etPassword.setError("密码长度不能少于6位");
            etPassword.requestFocus();
            return;
        }

        if (!password.equals(confirmPassword)) {
            etConfirmPassword.setError("两次输入的密码不一致");
            etConfirmPassword.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(userNickname)) {
            etNickname.setError("请输入昵称");
            etNickname.requestFocus();
            return;
        }

        // 显示进度条
        progressBar.setVisibility(View.VISIBLE);
        btnRegister.setEnabled(false);

        // 记录注册操作
        Log.d(TAG, "开始注册: 用户名=" + username + ", 昵称=" + userNickname + ", 使用邀请码=" + !TextUtils.isEmpty(inviteCode));

        // 注册逻辑
        if (!TextUtils.isEmpty(inviteCode)) {
            // 使用邀请码注册
            registerWithInvite(username, password, userNickname, inviteCode);
        } else {
            // 普通注册
            registerNormal(username, password, userNickname);
        }
    }

    private void registerNormal(String username, String password, String userNickname) {
        Log.d(TAG, "执行普通注册");
        userApi.register(username, password, userNickname).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                progressBar.setVisibility(View.GONE);
                btnRegister.setEnabled(true);
                
                Log.d(TAG, "注册响应: 状态码=" + response.code());
                
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        Log.d(TAG, "注册成功");
                        Toast.makeText(RegisterActivity.this, "注册成功！请登录", Toast.LENGTH_SHORT).show();
                        navigateToLogin();
                    } else {
                        String errorMsg = response.body().getMessage();
                        if (TextUtils.isEmpty(errorMsg)) {
                            errorMsg = "注册失败，请稍后重试";
                        }
                        Log.e(TAG, "注册失败: " + errorMsg);
                        Toast.makeText(RegisterActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    try {
                        String errorBody = response.errorBody() != null ? response.errorBody().string() : "未知错误";
                        Log.e(TAG, "注册失败: " + errorBody);
                        Toast.makeText(RegisterActivity.this, "注册失败: " + errorBody, Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        Log.e(TAG, "解析错误响应失败", e);
                        Toast.makeText(RegisterActivity.this, "注册失败，请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                btnRegister.setEnabled(true);
                Log.e(TAG, "注册网络请求失败", t);
                Toast.makeText(RegisterActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void registerWithInvite(String username, String password, String userNickname, String inviteCode) {
        Log.d(TAG, "执行带邀请码注册, 邀请码: " + inviteCode);
        userApi.registerWithInvite(username, password, userNickname, inviteCode).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                progressBar.setVisibility(View.GONE);
                btnRegister.setEnabled(true);
                
                Log.d(TAG, "邀请码注册响应: 状态码=" + response.code());
                
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        Log.d(TAG, "邀请码注册成功");
                        Toast.makeText(RegisterActivity.this, "注册成功！请登录", Toast.LENGTH_SHORT).show();
                        navigateToLogin();
                    } else {
                        String errorMsg = response.body().getMessage();
                        if (TextUtils.isEmpty(errorMsg)) {
                            errorMsg = "注册失败，请稍后重试";
                        }
                        Log.e(TAG, "邀请码注册失败: " + errorMsg);
                        Toast.makeText(RegisterActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    try {
                        String errorBody = response.errorBody() != null ? response.errorBody().string() : "未知错误";
                        Log.e(TAG, "邀请码注册失败: " + errorBody);
                        Toast.makeText(RegisterActivity.this, "注册失败: " + errorBody, Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        Log.e(TAG, "解析错误响应失败", e);
                        Toast.makeText(RegisterActivity.this, "注册失败，请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                btnRegister.setEnabled(true);
                Log.e(TAG, "邀请码注册网络请求失败", t);
                Toast.makeText(RegisterActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void navigateToLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }
}
